package com.hollysys.inspection.controller;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.hollysys.inspection.model.GtPicReqMode;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

@Slf4j
@RestController
@RequestMapping("rtsp-pic")
public class RtspPicController {

    @Value("${file-server.cache-enable}")
    private boolean cacheEnable;

    @Value("${file-server.root-dir}")
    private String fileRootDir;

    @Value("${file-server.files-mapping-dir:files}")
    private String filesMappingDir;

    private final TimedCache<String, String> PIC_CACHE = CacheUtil.newTimedCache(1000);

    @PostMapping
    public Resp<String> getPicFromRtsp(@RequestBody GtPicReqMode reqMode) {
        String rtspUrl = reqMode.getRtspUrl();
        String rtspUrlMd5 = SecureUtil.md5(rtspUrl);
        String key = "rtsp-pic:" + rtspUrlMd5;
        String pic = PIC_CACHE.get(key, false);
        if (StrUtil.isNotBlank(pic) && fileExists(pic)) {
            log.info("返回缓存的图片地址");
            return Resp.ok(pic);
        }

        log.info("不存在缓存图片，开始重新下载");
        TimeInterval timer = DateUtil.timer();
        try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(rtspUrl);
             Java2DFrameConverter converter = new Java2DFrameConverter()) {
            grabber.start();
            // 获取一帧
            BufferedImage image = converter.convert(grabber.grabImage());
            if (image != null) {
                File fileParent = new File(fileRootDir);
                FileUtil.mkdir(fileParent);
                String fileName = rtspUrlMd5 + "_" + System.currentTimeMillis() + ".JPEG";
                File tempFile = new File(fileParent, fileName);
                FileUtil.mkParentDirs(tempFile);

                // 保存为JPG
                String outputPath = tempFile.getAbsolutePath();
                ImageIO.write(image, "JPEG", new File(outputPath));
                log.info("图片提取成功: {}", outputPath);
                grabber.stop();

                log.info("文件是否存在：{}", FileUtil.exist(outputPath));
                String picUrl = "/" + filesMappingDir + "/" + fileName;
                if (cacheEnable) {
                    PIC_CACHE.put(key, picUrl);
                }
                return Resp.ok(picUrl);
            } else {
                grabber.stop();
                log.error("未能获取图像，rtspUrl：{}", rtspUrl);
                return Resp.failed("未能获取图像");
            }
        } catch (Exception e) {
            log.error("获取图像出现异常，rtspUrl：{}", rtspUrl, e);
            return Resp.failed("获取图像出现异常");
        } finally {
            long intervalRestart = timer.intervalRestart();
            log.info("截图耗时：{}毫秒", intervalRestart);
        }
    }

    private boolean fileExists(String picPath) {
        // /files/f2dc453444be4391a10e60fa8e7e6fdf.JPEG
        String path = fileRootDir + picPath.split(filesMappingDir)[1];
        return FileUtil.exist(path);
    }
}
